import java.util.ArrayList;
import java.util.PriorityQueue;

public class BM5 {
    public static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public static ListNode mergeKLists (ListNode[] lists) {
        PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
        for (ListNode node : lists) {
            if (node != null) {
                pq.offer(node);
            }
        }

        ListNode dummy = new ListNode(0);
        ListNode current = dummy;



        while (!pq.isEmpty()) {
            ListNode minNode = pq.poll();
            current.next = minNode;
            current = current.next;
            if (minNode.next != null) {
                pq.offer(minNode.next);
            }
        }

        return dummy.next;
    }

    public static void main(String[] args) {

        // 构建示例1中的链表数组
        ListNode[] lists1 = new ListNode[2];
        lists1[0] = new ListNode(1);
        lists1[0].next = new ListNode(2);
        lists1[0].next.next = new ListNode(3);
        lists1[1] = new ListNode(4);
        lists1[1].next = new ListNode(5);
        lists1[1].next.next = new ListNode(6);
        lists1[1].next.next.next = new ListNode(7);

        // 合并示例1中的链表数组
        ListNode mergedList1 = mergeKLists(lists1);

        // 输出合并后的链表
        while (mergedList1 != null) {
            System.out.print(mergedList1.val + " ");
            mergedList1 = mergedList1.next;
        }
        System.out.println();

        // 构建示例2中的链表数组
        ListNode[] lists2 = new ListNode[3];
        lists2[0] = new ListNode(1);
        lists2[0].next = new ListNode(2);
        lists2[1] = new ListNode(1);
        lists2[1].next = new ListNode(4);
        lists2[1].next.next = new ListNode(5);
        lists2[2] = new ListNode(6);

        // 合并示例2中的链表数组
        ListNode mergedList2 = mergeKLists(lists2);

        // 输出合并后的链表
        while (mergedList2 != null) {
            System.out.print(mergedList2.val + " ");
            mergedList2 = mergedList2.next;
        }
    }
}
